package com.jf.cloud.service.sysmanager.common.util;

import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.util.NodeList;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * IP 区域查询工具类
 * @author liwz at 2010-10-24
 *
 */
public class IPCheckService {
	private static Log log = LogFactory.getLog(IPCheckService.class);
	private static boolean IS_ALL_FLAG= false;
	static List<String> province = new ArrayList<String>();
	static
	{
		province.add("北京");
		province.add("天津");
		province.add("上海");
		province.add("重庆");
		province.add("河北");
		province.add("山西");
		province.add("辽宁");
		province.add("吉林");
		province.add("黑龙江");
		province.add("江苏");
		province.add("浙江");
		province.add("安徽");
		province.add("福建");
		province.add("江西");
		province.add("山东");
		province.add("河南");
		province.add("湖北");
		province.add("湖南");
		province.add("广东");
		province.add("海南");
		province.add("四川");
		province.add("贵州");
		province.add("云南");
		province.add("陕西");
		province.add("甘肃");
		province.add("青海");
		province.add("台湾");
		province.add("内蒙古");
		province.add("广西");
		province.add("西藏");
		province.add("宁夏");
		province.add("新疆");
		province.add("香港");
		province.add("澳门");
	}
	
	/**
	 * 
	 * @param IP 需要查询的ip地址 或者域名信息
	 * @return String 区域信息 如： 陕西省西安市
	 */
	public static String getIPAreaString(String IPorDomain){
		String return_value="";
		return_value = getIPAreaStringByTaobao(IPorDomain);
		return return_value;
	}
	
	public static String getIPAreaStringByIP138(String IPorDomain){
		String areaString = "";
		try {
			NodeFilter filter = new TagNameFilter("li");
			Parser parser = new Parser();
			parser.setURL("http://www.ip138.com/ips8.asp?ip="+IPorDomain+"&action=2");
			parser.setEncoding(parser.getEncoding());
			NodeList list = parser.extractAllNodesThatMatch(filter);
			for (int i = 0; i < list.size(); i++) {
				String temp = list.elementAt(i).toPlainTextString();
				if(temp.startsWith("本站主数据：")){
					areaString = temp.substring(6,temp.lastIndexOf(" "));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}	
		return areaString;		
	}
	
	public static String getIPAreaStringByPConline(String IPorDomain)
	{
		String areaString = "";
		try
		{
			String url = "http://whois.pconline.com.cn/jsLabel.jsp?ip=" + IPorDomain;
			HttpURLConnection urlConn = (HttpURLConnection) (new URL(url).openConnection());
			HttpURLConnection.setFollowRedirects(true);
			urlConn.setRequestMethod("GET");
			urlConn.setConnectTimeout(6000); // 6秒钟链接主机
			urlConn.setReadTimeout(5000);// 5秒钟读取内容超时
			InputStream in = urlConn.getInputStream();
			byte[] chByte = new byte[in.available()];
			in.read(chByte);
			areaString = new String(chByte).trim().split("=")[1];
			//log.info("根据IP获取的地址是:" + areaString);
			if(areaString.contains("局域网")) //根据测试要求，便于测试在局域网环境下测试
			{
				return "陕西";
			}else
			{
				areaString = findProvince(areaString);
				//log.info("匹配的省份是:" + areaString);
				return areaString;
			}
		} catch (Exception e)
		{
			//e.printStackTrace();
			return "";
		}
	}

	private static String findProvince(String areaString)
	{
		for (String str : province)
		{
			if (areaString.contains(str))
			{
				return str;
			}
		}
		throw new IllegalArgumentException("未获取到省份:" + areaString);
	}
	
	private static String getIPAreaStringByTaobao(String IPorDomain){
		String areaString = "";
		
	      try {
				String url = "http://ip.taobao.com/service/getIpInfo.php?ip="+IPorDomain;
				HttpURLConnection urlConn = (HttpURLConnection) (new URL(url).openConnection());
				HttpURLConnection.setFollowRedirects(true);
				urlConn.setRequestMethod("GET");
				urlConn.setConnectTimeout(6000); // 6秒钟链接主机
				urlConn.setReadTimeout(5000);// 5秒钟读取内容超时
				InputStream in = urlConn.getInputStream();
				byte[] chByte = new byte[in.available()];
				in.read(chByte);
				String c_area = new String(chByte).trim();
				c_area = c_area.substring(c_area.indexOf("{"));
				JSONObject jb  = JSONObject.fromObject(c_area).getJSONObject("data");
//				System.out.println(jb.toString());				
				//国家 区域 省 市 运营商
				String country = jb.getString("country");
				String area = jb.getString("area");
				String region = jb.getString("region");
				String city = jb.getString("city");
				String isp = jb.getString("isp");
//				areaString = country +" " +area+ " " +region+ " "+city+ " "+isp ;
				areaString = region+ " "+city;
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}		

		return areaString;		
	}	
	
	public static String getIPProvinceByTaobao(String ip)
	{
		String areaString = "";
		try
		{
			String url = "http://ip.taobao.com/service/getIpInfo.php?ip=" + ip;
			HttpURLConnection urlConn = (HttpURLConnection) (new URL(url).openConnection());
			HttpURLConnection.setFollowRedirects(true);
			urlConn.setRequestMethod("GET");
			urlConn.setConnectTimeout(10000); // 6秒钟链接主机
			urlConn.setReadTimeout(10000);// 5秒钟读取内容超时
			InputStream in = urlConn.getInputStream();
			byte[] chByte = new byte[in.available()];
			in.read(chByte);
			String c_area = new String(chByte).trim();
			c_area = c_area.substring(c_area.indexOf("{"));
			JSONObject jb = JSONObject.fromObject(c_area).getJSONObject("data");
			return jb.getString("region").substring(0, 2);
		} catch (Exception e)
		{
			e.printStackTrace();
		}
		return areaString;
	}
	/**
	 * 比较输入的两个ip或域名是不是在同一区域
	 * @param IPorDomain1 比较信息1
	 * @param IPorDomain2 比较信息2
	 * @return 区域相同返回 true ，否则返回 false
	 */
	public static boolean compareIPAreaInfo(String IPorDomain1, String IPorDomain2){
		boolean return_value = false;
		if(getIPAreaString(IPorDomain1).equals(getIPAreaString(IPorDomain2))){
			return_value = true;
		}
		return return_value;

	}	
	
	/**
	 * 比较输入的区域是不是在同一区域
	 * @param areaName1 比较信息1
	 * @param areaName2 比较信息2
	 * @return 区域相同返回 true ，否则返回 false
	 */
	public static boolean compareAreaInfo(String areaName1, String areaName2){
		boolean return_value = false;
		if(!StringUtil.notNull(areaName1) || !StringUtil.notNull(areaName2)) {
			return return_value;
		}
		//假如是精确比较
		if(IS_ALL_FLAG){
			if(areaName1.equals(areaName2)){
				return_value = true;
			}
		}else{
			String areaName1_temp = areaName1;
			String areaName2_temp = areaName2;
			if(areaName1.indexOf("省")>-1){
				areaName1_temp = new String(areaName1.substring(0,areaName1.indexOf("省")));
			}
			if(areaName2.indexOf("省")>-1){
				areaName2_temp = new String(areaName2.substring(0,areaName2.indexOf("省")));
			}
			if(areaName1.indexOf(areaName2_temp)>-1 || areaName2.indexOf(areaName1_temp)>-1){
				return_value = true;
			}
			System.out.print(areaName1_temp+"=="+areaName2_temp);
		}
		return return_value;

	}	
	
	/**
	 * 
	 * @param IP 需要查询的ip地址 或者域名信息
	 * @return String  电信/网通/铁通 等
	 */
	public static String getIPType(String IPorDomain){
		String typeString = "";
		try {
			NodeFilter filter = new TagNameFilter("li");
			Parser parser = new Parser();
			parser.setURL("http://www.ip138.com/ips8.asp?ip="+IPorDomain+"&action=2");
			parser.setEncoding(parser.getEncoding());
			NodeList list = parser.extractAllNodesThatMatch(filter);
			for (int i = 0; i < list.size(); i++) {
				String temp = list.elementAt(i).toPlainTextString();
				if(temp.startsWith("本站主数据：")){
					typeString = temp.substring(temp.lastIndexOf(" ")+1,temp.length());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}	
		return typeString;
	}	
 
}
